package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @Title: autoDxCustIssued*
 * @Description: 经营任务下发接口-按线程号
 * @author: tian*
 * @date 2021-12-16 11:00:00
 */
class apiTaskAssignJy implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTaskAssignJy.class);

    //任务下发主要方法
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 初始化返回参数
        String Syncpram = "";
        JSONObject result = new JSONObject();
        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + Syncpram);
        }
        String threadid = request.getParameter("threadid"); //传入线程号
        try {
            int loogNum = 0; //总数量
            int succNum = 0; //成功数量
            int failNum = 0; //失败数量
            long totalTime = System.currentTimeMillis();
            String rec_id = "";
            //2.经营待下发任务处理
            List accountList = eliteBean.chaxun_sql("select a.rec_id,a.customerid,a.task_type,a.task_guid,c1.customer_guid,i.intermediary_id,i.intermediary_type,c1.departmentid,c1.customertype2_id,c1.mobile,c.task_name,ifnull(c1.canceldate,'') as canceldate from Account_Information a left join pa_sms_task_batch c on a.thread_id=c.rec_guid  left join customer c1 on a.customerid=c1.CUSTOMER_ID left join pa_intermediary_info i on c1.intermediary=i.intermediary_id where a.deal_flag=0  and thread_id='" + threadid + "'  order by a.createtime desc  Limit 5000", "dataSource");
            loogNum = accountList.size();
            for (int i = 0; i < loogNum; i++) {
                long startTime = System.currentTimeMillis();
                int deal_flag = 0;
                String deal_result = "";
                String objective_guid = "";
                try {
                    Map accountMap = accountList.get(i);
                    rec_id = accountMap.get("rec_id");//处理任务主键
                    String customerid = accountMap.get("customerid");//资金账号
                    String customer_guid = accountMap.get("customer_guid");//客户id
                    String intermediary_id = accountMap.get("intermediary_id");//居间人编号
                    String intermediary_type = accountMap.get("intermediary_type");//居间人类型（1内部居间人2外部居间人）
                    String departmentid = accountMap.get("departmentid");//所属营业部(渠道来源)
                    String customertype2_id = accountMap.get("customertype2_id");//客户类型（0个人客户1一般法人3特殊法人3资管户）
                    String mobile = accountMap.get("mobile");//联系号码

                    //任务类型取自配置表
                    String level ="3";//规则类型（1常规名单2特定名单3活动名单）  此处默认为活动名单3
                    String node_id ="C29SDB"; //默认赋值活动名单节点
                    String task_type = accountMap.get("task_type");//任务类型编号
                    String code_name = accountMap.get("task_name");//任务类型名称


                    String canceldate = accountMap.get("canceldate");//销户时间
                    int canceldateLen=canceldate.length();

                    log.debug("【开始执行下发】资金账号：" + customerid + "|任务类型：" + task_type + "|居间人类型：" + intermediary_type + "所属营业部：" + departmentid + "node_id:" + node_id + "客户类型:" + customertype2_id);

                    if (customer_guid == '' || customer_guid == null) {
                        deal_flag = -2;
                        deal_result = "下发失败-资金账号:" + customerid + ",根据资金账号在集中作业平台未找到客户信息";
                    } else if (customertype2_id != '0') {
                        deal_flag = -1;
                        deal_result = "下发失败-资金账号:" + customerid + ",客户类型非个人客户不允许下发";
                    } else if (intermediary_type == '2') {
                        deal_flag = -1;
                        deal_result = "下发失败-资金账号:" + customerid + ",居间人" + intermediary_id + "为外部居间人剔除任务";
                    }else if (canceldateLen==8) {
                        deal_flag = -1;
                        deal_result = "下发失败-资金账号:" + customerid + ",该客户已销户不做下发"+canceldate;
                    } else {
                        // 通过资金账号查询客户经理关系表，判断归属客户经理名单是否在系统参数维护的不下发的名称中
                        String checkIsFilterSQL = '''Select t.f_Distribute_Id,
                                                   t.f_Distribute_Name,
                                                   S2.Staff_Id,
                                                   S2.Defaultrolegroup,
                                                   S2.Staffname,
                                                   Find_In_Set(Ifnull(t.f_Distribute_Name, ''), Ifnull(R1.Parametervalue, '')) As isFilterFlag
                                              From Dws.t_Bfs_Cust_Staff_Relations t
                                              Left Join Staff S2
                                                On (t.f_Distribute_Id = S2.Pa_Userid Or t.f_Distribute_Name = S2.Staffname)
                                              Left Join Sysc_Parameter R1
                                                On R1.Parameter_Id = 'DX_STG\'
                                               And R1.Rolegroup_Id = '######\'
                                             Where t.Investorid = \'''' + customerid + '''\' Limit 1''';
                        List checkIsFilterRes = eliteBean.chaxun_sql(checkIsFilterSQL, "dataSource");

                        String isFilterFlag = "0";
                        if (checkIsFilterRes.size() > 0) {
                            Map checkIsFilterMap = checkIsFilterRes.get(0);
                            isFilterFlag = checkIsFilterMap.get("isFilterFlag");
                        }

                        if (isFilterFlag == "0") {
                            //使用资金账号校验是否存在与资金账号同类型的任务
                            String checkTask = "";
                            String checkSameTask = "select e.elitetask_guid from elitetask e left join customer c on c.customer_guid=e.customer_guid  where c.customer_id='" + customerid + "'  and e.PA_TASKTYPE='" + task_type + "'";
                            List checkTaskRes = eliteBean.chaxun_sql(checkSameTask, "dataSource");
                            if (checkTaskRes.size() > 0) {
                                Map checkTaskMap = checkTaskRes.get(0);
                                checkTask = checkTaskMap.get("elitetask_guid");
                            }

                            //使用资金账号校验客户是否被加入过无服务意向池、问题客户池、放弃池
                            String checkTaskPoolSql = "select count(*) as checkcount from elitetask e left join customer c on c.customer_guid=e.customer_guid  where c.customer_id='" + customerid + "'  and e.PA_TASK_POOL in ('JYDXWF','JYDXWT','JYDXFQ')";
                            List checkPoolRes = eliteBean.chaxun_sql(checkTaskPoolSql, "dataSource");
                            Map checkPoolMap = checkPoolRes.get(0);
                            Integer checkPoolcount = checkPoolMap.get("checkcount");

                            log.debug("checkTask:" + checkTask + "|" + "checkPoolcount:" + checkPoolcount);

                            if (!KHUtil.isNull(checkTask) && task_type != 'DX_03') {
                                deal_flag = -1;
                                deal_result = "下发失败-资金账号:" + customerid + ",已存在相同类型的" + code_name + "任务无需再次下发";
                            } else if (checkPoolcount > 0) {
                                deal_flag = -1;
                                deal_result = "下发失败-资金账号:" + customerid + ",存在无服务意向记录，" + code_name + "任务无需再次下发";
                            } else if (!KHUtil.isNull(checkTask) && task_type == 'DX_03') {
                                //将原有的下发日期更新为今天
                                String updateSql = "update elitetask set createddate=now() where elitetask_guid='" + checkTask + "'";
                                Integer upRow = eliteBean.update(updateSql, "dataSource");
                                if (upRow > 0) {
                                    deal_flag = 1;
                                    deal_result = "下发成功-资金账号:" + customerid + ",原有上日激活名单再次下发";
                                } else {
                                    deal_flag = -1;
                                    deal_result = "下发失败-资金账号:" + customerid + ",原有上日激活名单再次下发失败";
                                }

                            } else {
                                //优先下发至原有客户经理
                                log.debug("开始原客户经理下发流程：" + customerid);
                                Map oldCustomerManageMap1 = oldCustomerManager(eliteBean, customer_guid, task_type, mobile, node_id, customerid);
                                deal_flag = oldCustomerManageMap1.get("deal_flag").toInteger();
                                deal_result = oldCustomerManageMap1.get("deal_result");

                                //共16种任务，其中14类常规名单如果是新客户从未有人跟进过则继续执行后续下发流程，另外两类（活动名单及特殊名单）只下发至客户经理不再继续执行新客任务
                                if (level == '1' && deal_flag == -1) {
                                    log.debug("开始新客下发流程：" + customerid);
                                    Map newCustomerManagerMap1 = newCustomerManager(eliteBean, customerid, intermediary_type, intermediary_id, departmentid, node_id, objective_guid, customer_guid, task_type, mobile);
                                    deal_flag = newCustomerManagerMap1.get("deal_flag").toInteger();
                                    deal_result = newCustomerManagerMap1.get("deal_result");
                                }
                                //由于平安渠道数据提供有延时问题导致名单按照渠道规则下发不正确，故按照平安从综合管理平台同步过来的数据修改客户经理，原有的下发流程暂不做调整，下发完成之后更新
                                changeCustomerManager(eliteBean, customerid);
                            }
                        } else {
                            deal_flag = -1;
                            deal_result = "下发失败-资金账号:" + customerid + ",满足客户经理（居间信息）过滤规则，放弃下发处理";
                        }
                    }
                } catch (Exception e) {
                    deal_flag = -1;
                    deal_result = "下发失败处理异常" + e.printStackTrace();
                    log.error("【执行结束】当前名单" + i + " 执行处理异常!", e.printStackTrace());
                }

                //任务耗时统计
                long endTime = System.currentTimeMillis();
                String reOutIntermediarySql = "Update Account_Information Set Deal_Time = Now(), Deal_Flag = " + deal_flag + ", Deal_Result = '" + deal_result + "-耗时:" + (endTime - startTime) + "' Where Rec_Id = '" + rec_id + "'";
                eliteBean.update(reOutIntermediarySql, "dataSource");
                log.debug("【执行结束】本次耗时:" + (endTime - startTime));

                //统计执行数量
                if (deal_flag == 1) {
                    succNum++;
                } else if (deal_flag == -1) {
                    failNum++;
                }
            }
            String Result = "经营任务数据处理完成,总数:" + loogNum + " 成功数量:" + succNum + " 失败数量:" + failNum + "-处理时长(毫秒):" + (System.currentTimeMillis() - totalTime);
            result.put("code", 1);
            result.put("msg", Result);

        } catch (Exception e) {
            log.error("处理异常!", e);
            result.put("code", "-1");
            result.put("msg", "经营下发任务-按线程号处理异常-线程号:" + threadid + "," +e.printStackTrace());
        }
        return result.toString();
    }

    //新增-由于平安渠道数据提供有延时问题导致名单按照渠道规则下发不正确，故按照平安从综合管理平台同步过来的数据修改客户经理
    public static void changeCustomerManager(EliteBean eliteBean, String customerid) {

        //查询经营的非开户名单任务的资金账号在平安另一个系统对应的客户经理，添加至临时表
        String selectCustomerManagerSQL = "SELECT c.customer_guid,e.elitetask_guid,c.customer_id,e.handleby_id,s.staffname,t.f_distribute_id,t.f_distribute_name, " +
                "S2.STAFF_ID as fdn,S2.STAFFNAME as clp " +
                "FROM elitetask e " +
                "LEFT JOIN customer c ON e.customer_guid = c.customer_guid " +
                "left join dws.t_bfs_cust_staff_relations t on c.customer_id=t.investorid " +
                "left join staff s on e.HANDLEBY_ID=s.STAFF_ID " +
                "left join staff s2 on (t.f_distribute_id=s2.pa_userid or t.f_distribute_name = s2.STAFFNAME) " +
                "WHERE e.CREATEDDATE >=DATE_FORMAT(now(),'%Y-%m-%d 00:00:00') " +
                "AND e.map_id = 'M4F19B' " +
                "and e.CURSTEP_ID_MAP!='J4920T' " +
                "and S2.STAFF_ID is not null " +
                "and t.investorid='" + customerid + "' limit 1 ";
        List CustomerManagerList = eliteBean.chaxun_sql(selectCustomerManagerSQL, "dataSource");
        for (int i = 0; i < CustomerManagerList.size(); i++) {
            Map accountMap = CustomerManagerList.get(i);
            String customer_guid = accountMap.get("customer_guid");//客户编号
            String elitetask_guid = accountMap.get("elitetask_guid");//任务编号
            String customer_id = accountMap.get("customer_id");//资金账号
            String handleby_id = accountMap.get("handleby_id");//任务当前处理人
            String staffname = accountMap.get("staffname");//任务当前处理人姓名
            String f_distribute_id = accountMap.get("f_distribute_id");//平安客户经理编号
            String f_distribute_name = accountMap.get("f_distribute_name");//平安客户经理姓名
            String fdn = accountMap.get("fdn");//平安客户经理对应电销的staff_id
            String clp = accountMap.get("clp");//平安客户经理对应电销的坐席姓名

            if (handleby_id != fdn) {
                String updateEtaCustMannagerSQL = "update elitetask e set e.HANDLEBY_ID='" + fdn + "' where e.CUSTOMER_GUID='" + customer_guid + "' and e.MAP_ID='M4F19B'  and e.CREATEDDATE>=DATE_FORMAT(now(),'%Y-%m-%d 00:00:00') and e.CURSTEP_ID_MAP!='J4920T'";
                int updateEtaCustMannagerRow = eliteBean.update(updateEtaCustMannagerSQL, "dataSource");
                log.debug("更新elitetask客户经理条数：" + updateEtaCustMannagerRow);

                String updateObjCustMannagerSQL = "update objective e  set e.HANDLEBY_ID='" + fdn + "' where e.CUSTOMER_GUID='" + customer_guid + "' and e.MAP_ID='M4F19B' and e.CREATEDDATE>=DATE_FORMAT(now(),'%Y-%m-%d 00:00:00') and e.CURSTEP_ID_MAP!='J4920T'";
                int updateObjCustMannagerRow = eliteBean.update(updateObjCustMannagerSQL, "dataSource");
                log.debug("更新objective客户经理条数：" + updateObjCustMannagerRow);

                //新增客户经理变更历史
                String addTempJyHisSQL = "insert into hst_Service_hislist(sys_guid,CUSTOMER_ID,customer_guid,used_staffid,apply_time,MODIFIEDBY,context,Reviewer_staffid,Reviewer_time) VALUES(uuid(),'" + customer_id + "','" + customer_guid + "','" + fdn + "',now(),'SELITE','经营自动从综合管理平台同步','SELITE',now()) ";
                int addTempJyHisRow = eliteBean.update(addTempJyHisSQL, "dataSource");
                log.debug("新增hst_Service_hislist条数：" + addTempJyHisRow);
            }
        }
    }

    //经营14类任务下发
    public static Map<String, String> newCustomerManager(EliteBean eliteBean, String customerid, String intermediary_type, String intermediary_id, String departmentid, String node_id, String objective_guid, String customer_guid, String task_type, String mobile) {
        boolean newCustDeal3;
        String deal_result = "";
        String deal_flag = "";
        String se_handlegroup_id = "";
        String se_handleby_id = "";
        String rule_rec_id = "";
        Map<String, String> map = new HashMap<String, String>();

        //内部居间人，根据名单渠道查询是否存在规则
        def findChannel = "Select Rule_Id, Rule_Name From Hst_Rule_Issue Where Rule_State = 1 And Find_In_Set(binary '" + departmentid + "', Code_Id) > 0 Order By Order_Adjustment Limit 1";
        List channelList = eliteBean.chaxun_sql(findChannel, "dataSource");
        //查询到渠道规则按照渠道规则下发
        int re_channelsize = channelList.size();
        log.debug("渠道规则条数：" + re_channelsize);
        if (re_channelsize > 0) {
            log.debug("内部居间人名单，且存在渠道规则");
            String rule_id = channelList.get(0).get("Rule_Id");//渠道规则编号

            //检查下发规则并初始化
            ruleAssignInit(eliteBean, rule_id);

            // (按渠道规则平均)取当前名单下发最少的坐席（不支持一人多组）
            def getAssginStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id" +
                    "  From Hst_Rule_Issue_Control R1" +
                    "  Left Join Staffrolegroup R2" +
                    "    On R1.Staff_Id = R2.Staff_Id" +
                    "  Left Join Staff R3" +
                    "    On R1.Staff_Id = R3.Staff_Id" +
                    " Where Rule_Id = " + rule_id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                    " Order By Assign_Num,Staff_Id Limit 1";
            List getAssginStaffList = eliteBean.chaxun_sql(getAssginStaffSQL, "dataSource");

            if (getAssginStaffList.size() > 0) {
                Map getAssginStaffMap = getAssginStaffList.get(0);
                rule_rec_id = getAssginStaffMap.get("Rec_Id");
                se_handlegroup_id = getAssginStaffMap.get("Rolegroup_Id");
                se_handleby_id = getAssginStaffMap.get("Staff_Id");
                log.debug("[内部居间人名单,根据规则匹配到下发坐席为] Rolegroup_Id:" + se_handlegroup_id + " Staff_Id:" + se_handleby_id + "rule_id:" + rule_id);

                //居间人为内部人员，取渠道规则中名单较少的坐席，实现平均分配
                newCustDeal3 = newCustomerDeal(eliteBean, se_handlegroup_id, se_handleby_id, node_id, objective_guid, customer_guid, task_type, rule_rec_id, mobile, customerid);
                if (newCustDeal3) {
                    map.put("deal_flag", "1");
                    map.put("deal_result", "下发成功-资金账号:" + customerid + ",根据渠道将名单下发至" + se_handleby_id);
                }
            } else {
                map.put("deal_flag", "-1");
                map.put("deal_result", "下发失败-资金账号:" + customerid + ",存在规则但未正确匹配到坐席");
            }

        } else {
            String defaultrule_id = '1';
            log.debug("内部居间人名单,但不存在渠道规则,需要将名单平均分配给电销坐席");
            //检查下发规则并初始化
            ruleAssignInit(eliteBean, defaultrule_id);
            // 默认平均分配，取当前名单下发最少的坐席（不支持一人多组）
            def getAverageStaffSQL = "Select R1.Rec_Id, R2.Rolegroup_Id, R1.Staff_Id, R3.counselor_id" +
                    "  From Hst_Rule_Issue_Control R1" +
                    "  Left Join Staffrolegroup R2" +
                    "    On R1.Staff_Id = R2.Staff_Id" +
                    "  Left Join Staff R3" +
                    "    On R1.Staff_Id = R3.Staff_Id" +
                    " Where Rule_Id = " + defaultrule_id + "" +
                    "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')" +
                    " Order By Assign_Num,Staff_Id Limit 1";
            List getAverageStaffSQLList = eliteBean.chaxun_sql(getAverageStaffSQL, "dataSource");

            if (getAverageStaffSQLList.size() > 0) {
                Map getAverageStaffMap = getAverageStaffSQLList.get(0);
                rule_rec_id = getAverageStaffMap.get("Rec_Id");
                se_handlegroup_id = getAverageStaffMap.get("Rolegroup_Id");
                se_handleby_id = getAverageStaffMap.get("Staff_Id");

                log.debug("[内部居间人名单,未找到渠道规则，按默认平均分配规则分配] Rolegroup_Id:" + se_handlegroup_id + " Staff_Id:" + se_handleby_id + "rule_id:" + defaultrule_id);

                newCustDeal3 = newCustomerDeal(eliteBean, se_handlegroup_id, se_handleby_id, node_id, objective_guid, customer_guid, task_type, rule_rec_id, mobile, customerid);
                if (newCustDeal3) {
                    map.put("deal_flag", "1");
                    map.put("deal_result", "下发成功-资金账号:" + customerid + ",未找到渠道规则，按默认平均分配规则分配至" + se_handleby_id);
                } else {
                    map.put("deal_flag", "-1");
                    map.put("deal_result", "下发失败-资金账号:" + customerid + ",默认平均分配失败");
                }
            } else {
                map.put("deal_flag", "-1");
                map.put("deal_result", "下发失败-资金账号:" + customerid + ",未找到默认平均分配规则");
            }
        }
        return map;
    }

    //将任务下发至原有客户经理
    public static Map<String, String> oldCustomerManager(EliteBean eliteBean, String customer_guid, String task_type, String mobile, String node_id, String customerid) {
        Map<String, String> map = new HashMap<String, String>();
        List ruleCheckList = eliteBean.chaxun_sql("select handlegroup_id,handleby_id,objective_guid from elitetask where customer_guid='" + customer_guid + "' and pa_tasktype in(select code_id from c_codetables " +
                "where Use_Type='电销外呼类型') order by MODIFIEDDATE desc  limit 1", "dataSource");
        if (ruleCheckList.size() > 0) {
            boolean newCustDeal1;
            String objective_guid = "";
            String se_handlegroup_id = "";
            String rule_rec_id = "";
            String se_handleby_id = "";
            String deal_result = "";
            String deal_flag = "";
            //存在外呼任务则直接将名单下发给原来跟进过此客户的坐席
            Map ruleCheckMap = ruleCheckList.get(0);
            objective_guid = ruleCheckMap.get("objective_guid");
            se_handlegroup_id = ruleCheckMap.get("handlegroup_id");
            se_handleby_id = ruleCheckMap.get("handleby_id");
            log.debug("已存在过外呼任务，按照原跟进坐席下发" + objective_guid);
            newCustDeal1 = newCustomerDeal(eliteBean, se_handlegroup_id, se_handleby_id, node_id, objective_guid, customer_guid, task_type, rule_rec_id, mobile, customerid);
            if (newCustDeal1) {
                map.put("deal_flag", "1");
                map.put("deal_result", "下发成功-资金账号:" + customerid + ",下发至原有客户经理" + se_handleby_id);
            }
        } else {
            map.put("deal_flag", "-1");
            map.put("deal_result", "下发失败-资金账号:" + customerid + ",未找到对应的客户经理");
        }
        return map;
    }

    //创建任务(objective及eliteask),新客发送客户经理短信
    public static boolean newCustomerDeal(EliteBean eliteBean, String r_Rolegroup_Id, String r_Staff_Id, String node_id, String Objective_Guid, String Customer_Guid, String task_type, String Rec_Id, String mobile, String customer_id) {
        boolean reFlag = true;
        // 生成相关ID
        String Temp_Guid = KHUtil.getRandomString(31).toUpperCase();
        String re_Objective_Guid = "";

        if (Objective_Guid == "") {
            re_Objective_Guid = "OBJE_" + Temp_Guid;
        } else {
            re_Objective_Guid = Objective_Guid;
        }
        String EliteTask_Guid = "TASK_" + Temp_Guid;
        String[] custTaskDealSQL = new String[6];

        try {
            if (Objective_Guid == '' || Objective_Guid == null) {
                // 插入Objective表
                custTaskDealSQL[1] = "Insert Into Objective" +
                        "  (Objective_Guid," +
                        "   Objectivetype_Id," +
                        "   Handleby_Id," +
                        "   Handlegroup_Id," +
                        "   Priority_Id," +
                        "   Expireddate," +
                        "   Customer_Guid," +
                        "   Objectivestatus," +
                        "   Iscontact," +
                        "   Trytimes," +
                        "   Successfulcontacttimes," +
                        "   Createdby," +
                        "   Createddate," +
                        "   Obstatus," +
                        "   Failure_Attempt," +
                        "   Contact_Customer_Guid," +
                        "   Passflag," +
                        "   Lastassigndate," +
                        "   Failstatus," +
                        "   Successstatus," +
                        "   Owner," +
                        "   Workorderframe_Id," +
                        "   Category," +
                        "   Forecastdate," +
                        "   Workorderid," +
                        "   Workordertype1," +
                        "   Workordertype2," +
                        "   Workordertype3," +
                        "   Workordertype4," +
                        "   Objectivesubstatus," +
                        "   Map_Id," +
                        "   Curstep_Id_Map," +
                        "   Max_Attempt," +
                        "   Nocontacttry," +
                        "   Allocation_Pool," +
                        "   Appointment," +
                        "   PA_TASKTYPE)" +
                        "Values" +
                        "  ('" + re_Objective_Guid + "'," +
                        "   'RE0TX1'," +
                        "   '" + r_Staff_Id + "'," +
                        "   '" + r_Rolegroup_Id + "'," +
                        "   'NORMAL'," +
                        "   Date_Add(Now(), Interval 1 Day)," +
                        "   '" + Customer_Guid + "'," +
                        "   'OPEN'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   'SELITE'," +
                        "   Now()," +
                        "   'OPEN'," +
                        "   999," +
                        "   ''," +
                        "   0," +
                        "   Null," +
                        "   '0'," +
                        "   '0'," +
                        "   ''," +
                        "   'M4F19B'," +
                        "   'CASE'," +
                        "   now()," +
                        "   Concat('PA', Date_Format(Now(), '%Y%m%d%H'), '-', Lpad(Floor(Rand() * 10000), 4, '0'))," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   ''," +
                        "   'OPEN'," +
                        "   'M4F19B'," +
                        "   '" + node_id + "'," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   0," +
                        "   '" + task_type + "')";
            }
            // 插入EliteTask表
            custTaskDealSQL[2] = "Insert Into Elitetask" +
                    "  (Elitetask_Guid," +
                    "   Objective_Guid," +
                    "   Objectivetype_Id," +
                    "   Expectstarttime," +
                    "   Expectendtime," +
                    "   Obstatus," +
                    "   Recordstatus," +
                    "   Attempt," +
                    "   Max_Attempt," +
                    "   Handleby_Id," +
                    "   Handlegroup_Id," +
                    "   Createdby," +
                    "   Createddate," +
                    "   Failure_Attempt," +
                    "   Comments," +
                    "   Customer_Guid," +
                    "   Localtrycount," +
                    "   Lastassigndate," +
                    "   Workorderframe_Id," +
                    "   Curstepstatus," +
                    "   Curstep_Id," +
                    "   Stepforecastdate," +
                    "   Curstep_Id_Map," +
                    "   Map_Id," +
                    "   Objectivesubstatus," +
                    "   Elitetaskstatus," +
                    "   Obflag,Maintaskstep_Id_Map," +
                    "   PA_TASKTYPE)" +
                    "Values" +
                    "  ('" + EliteTask_Guid + "'," +
                    "   '" + re_Objective_Guid + "'," +
                    "   'RE0TX1'," +
                    "   Now()," +
                    "   Date_Add(Now(), Interval 3 Day)," +
                    "   'OPEN'," +
                    "   0," +
                    "   0," +
                    "   999," +
                    "   '" + r_Staff_Id + "'," +
                    "   '" + r_Rolegroup_Id + "'," +
                    "   'SELITE'," +
                    "   Now()," +
                    "   999," +
                    "   ''," +
                    "   '" + Customer_Guid + "'," +
                    "   0," +
                    "   Now()," +
                    "   ''," +
                    "   'OPEN'," +
                    "   'ONA0KD'," +
                    "   Now()," +
                    "   '" + node_id + "'," +
                    "   'M4F19B'," +
                    "   'OPEN'," +
                    "   'OPEN'," +
                    "   1,'','" + task_type + "')";

            //渠道规则均分
            if (Rec_Id != "" && Rec_Id != null) {
                custTaskDealSQL[3] = "Update Hst_Rule_Issue_Control Set Assign_Num = Assign_Num + 1, Last_Check_Time = Now() Where Rec_Id = " + Rec_Id;
            }

            String eta_id = "";
            String re_path = "";
            //发送二维码开关
            String QrCode = KHDBConfig.getParam(eliteBean, "QRCODE");
            if (QrCode == "1") {
                //查询当前客户为新客从未下发过任务时发送客户经理短信
                List chenkTaskList = eliteBean.chaxun_sql("select elitetask_guid,HANDLEBY_ID from elitetask where customer_guid='" + Customer_Guid + "' and pa_tasktype in(select code_id from c_codetables where Use_Type='电销外呼类型') limit 1", "dataSource");
                if (chenkTaskList.size() <= 0) {
                    List docList = eliteBean.chaxun_sql("select doctemplate_id,documentpath,doctemplate2 from Doctemplate where DOCTEMPLATE_ID='QH220215005'", "dataSource");
                    if (docList.size() > 0) {

                        Map docMap = docList.get(0);
                        String doctemplate_id = docMap.get("doctemplate_id");//模板ID
                        String documentpath = docMap.get("documentpath"); //模板内容
                        String doctemplate2 = docMap.get("doctemplate2"); //模板字段

                        // 调用API获取小程序url
                        String post_body = '''{"path":"pages/indexPoster/index",''' + ''' "query":"recid=''' + r_Staff_Id + '''",''' + ''' "is_expire":true,''' + ''' "expire_type":1,''' + ''' "expire_interval":10}''';
                        log.info("post_body:" + post_body);

                        String wxMinipUrl = KHDBConfig.getAPIURL(eliteBean, "API-WXMiniPURL");
                        String wxMinipUrlResult = Util.doHttpPost(wxMinipUrl, post_body, "UTF-8", 5000, 0);
                        JSONObject wxMinipUrlJson = new JSONObject(wxMinipUrlResult);
                        String re_code = wxMinipUrlJson.getInt("errcode");
                        if (re_code == 0) {
                            re_path = wxMinipUrlJson.getString("url_link");
                        } else {
                            log.debug("获取小程序url结果：" + wxMinipUrlJson.getString("errmsg"));
                        }
                        String re_documentpath = '''{"''' + doctemplate2 + '''":"''' + re_path + '''"}''';

                        custTaskDealSQL[4] = "INSERT INTO DOCUMENTOUT (DOCUMENTOUT_GUID, DOCTYPE, STATUS, TRIALCOUNT, TRIALCOUNTLIMIT, DOCUMENTPATH, HANDLEBY_ID, HANDLEGROUP_ID, CUSTOMER_GUID, CREATEDBY, CREATEDDATE, EXPECTEDSTARTDATE, DOCUMENTTO, LASTTRYDATETIME, sub_doctype, MSGID, TEMPLATE_ID, DOCUMENTPATH2, poster_guid,send_type) VALUES(uuid(), 3, 0, 0, 3,'" + documentpath + "','SELITE','SYSTEM','" + Customer_Guid + "','SELITE', now(), now(), '" + mobile + "',now(), '',REPLACE(unix_timestamp(current_timestamp(3)),'.',''),'" + doctemplate_id + "','" + re_documentpath + "','','1')";

                    }
                }
            }
            //新增分配历史
            custTaskDealSQL[5] = "insert into hst_Service_hislist(sys_guid,CUSTOMER_ID,customer_guid,used_staffid,apply_time,MODIFIEDBY,context,Reviewer_staffid,Reviewer_time) VALUES(uuid(),'" + customer_id + "','" + Customer_Guid + "','" + r_Staff_Id + "',now(),'SELITE','经营任务自动下发','SELITE',now()) ";

            int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
            log.debug("新客户入库批量处理SQL返回结果：" + batchSQLResult.toString());

            //检查是否具有冲突任务，有冲突任务则将原有冲突任务放入放弃池
            boolean reCheck = checkOldTask(eliteBean, Customer_Guid, task_type);
            log.error("冲突任务检查结果!" + reCheck);

        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }

        return reFlag;
    }

    //检查几类有冲突的任务（开户-首次交易）（一个月不交易任务-三个月不交易）（三个月不交易-半年不交易）
    public static boolean checkOldTask(EliteBean eliteBean, String Customer_Guid, String task_type) {
        boolean reFlag = true;
        String check_task_type = "";
        //如当前客户下发的任务为首次交易名单则检查是否有开户名单任务
        if (task_type == "DX_02") {
            check_task_type = "DX_01";
        }
        if (task_type == "DX_06") {
            check_task_type = "DX_05";
        }
        if (task_type == "DX_07") {
            check_task_type = "DX_06";
        }
        try {

            String[] checkOldTaskSql = new String[2];

            //根据当前客户的客户编号以及任务类型查询是否有冲突的任务将其放入放弃池
            String checkOldTaskSQL = "select elitetask_guid,objective_guid,pa_tasktype from elitetask where PA_TASKTYPE='" + check_task_type + "' and customer_guid='" + Customer_Guid + "'";
            List getOldTaskList = eliteBean.chaxun_sql(checkOldTaskSQL, "dataSource");
            if (getOldTaskList.size() > 0) {
                Map ruleCheckMap = getOldTaskList.get(0);
                String elitetask_guid = ruleCheckMap.get("elitetask_guid");
                String objective_guid = ruleCheckMap.get("objective_guid");
                checkOldTaskSql[1] = "update elitetask set CURSTEPSTATUS='END' where elitetask_guid='" + elitetask_guid + "' and PA_TASKTYPE='" + check_task_type + "' ";
                //checkOldTaskSql[1] = "update elitetask set handleby_id='000258',handlegroup_id='SYSTEM' where elitetask_guid='" + elitetask_guid + "' and PA_TASKTYPE='" + check_task_type + "' ";
                //checkOldTaskSql[2] = "update objective set handleby_id='000258',handlegroup_id='SYSTEM' where objective_guid='" + objective_guid + "' ";
                int[] row1 = eliteBean.updateBatch(checkOldTaskSql, "dataSource");
                log.debug("已将具有冲突的任务结束：" + elitetask_guid + "|" + check_task_type + "|" + row1.toString());
            } else {
                log.debug("当前任务无冲突可直接下发至坐席：" + Customer_Guid + "|" + task_type);
            }
        } catch (Exception e) {
            log.error("新客户入库异常!", e);
            reFlag = false;
        }
        return reFlag
    }

    //规则下发数据初始化
    public static boolean ruleAssignInit(EliteBean eliteBean, String Rule_Id) {
        boolean reFlag = true;

        //新增判断坐席B岗接任时间的逻辑截止状态、及离职人员默认不分配
        //A.-如果有离职人员 则直接关闭其分配状态-- 是否开启自动分配 0开启 1关闭
        String updatestaffstate1SQL = "update staff set auto_allocation=1 Where auto_allocation=0 And workstatus!='ONLINE'";
        eliteBean.update(updatestaffstate1SQL, "dataSource");

        //B.-如果有B岗角色接任时间到期 则更新企状态为自动开启分配 +清空时间维护
        String updatestaffstate2SQL = "update staff set auto_allocation=0,starttime=null,endtime=null Where auto_allocation=1  And starttime <now() And endtime<now()";
        eliteBean.update(updatestaffstate2SQL, "dataSource");

        // 初始化（1~4）下发记录表（这里默认按每天清零）
        // 1-查找当前规则配置的坐席
        String ruleStaffSQL = "Select Case When R1.Staff_Id Is Null Or R1.Staff_Id = '' Then R2.Staff_Id Else R1.Staff_Id End As ruleStaff" +
                " From Hst_Rule_Issue R1" +
                " Left Join (Select R4.Rule_Id, Group_Concat(Distinct R3.Staff_Id) As Staff_Id" +
                "    From Rolegroup R1" +
                "    Left Join Staffrolegroup R2 On R1.Rolegroup_Id = R2.Rolegroup_Id" +
                "    Left Join Staff R3 On R2.Staff_Id = R3.Staff_Id" +
                "    Left Join Hst_Rule_Issue R4 On Find_In_Set(R1.Rolegroup_Id, R4.Rolegroup) > 0" +
                "    Where R1.Status = 1 And ((R3.auto_allocation = 0) " +
                "    or (R3.auto_allocation = 1 And R3.starttime>now() And R3.endtime>now() And R3.starttime is not null And R3.endtime is not null)" +
                "    or (R3.auto_allocation = 1 And R3.starttime<now() And R3.endtime<now() And R3.starttime is not null And R3.endtime is not null))" +
                "    And R3.Workstatus = 'ONLINE'" +
                "    And R4.Rule_Id = " + Rule_Id + ") R2" +
                " On R1.Rule_Id = R2.Rule_Id And (R1.Staff_Id Is Null Or R1.Staff_Id = '')" +
                " Where R1.Rule_Id = " + Rule_Id + "";

        List ruleStaffList = eliteBean.chaxun_sql(ruleStaffSQL, "dataSource");

        Map ruleStaffMap = ruleStaffList.get(0);
        log.debug("ruleStaffMap:" + ruleStaffMap);
        String ruleStaff = ruleStaffMap.get("ruleStaff");
        log.debug("ruleStaff:" + ruleStaff);
        //处理Assign_Num
        def selectassignnumSQL = "select case when count(*)=0 then 0 else  round(sum(assign_num)/count(*)) end as assignnum from hst_rule_issue_control  Where Rule_Id = " + Rule_Id + "  And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        def selectassignnumresult = eliteBean.chaxun_sql(selectassignnumSQL, "dataSource");
        def assignnum = 0;
        if (selectassignnumresult.size() > 0) {
            assignnum = selectassignnumresult.get(0).get("assignnum");
        }
        log.debug("assignnum:" + assignnum);

        // 2-将不在下发规则表中不存在的坐席补充，防止中途规则配置的人或组修改添加
        String insertStaffSQL = "Insert Into Hst_Rule_Issue_Control" +
                "  (Rule_Id, Staff_Id, Assign_Date, Assign_Num,assign_yynum, Last_Check_Time)" +
                "  Select " + Rule_Id + ", Staff_Id, Date_Format(Now(), '%Y-%m-%d'), '" + assignnum + "', 0, Now()" +
                "  From Staff" +
                "  Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "  And Staff_Id Not In (Select Staff_Id From Hst_Rule_Issue_Control Where Rule_Id = " + Rule_Id + " And Assign_Date = Date_Format(Now(), '%Y-%m-%d'))";
        log.debug("insertStaffSQL:" + insertStaffSQL);
        int newStaffNum = eliteBean.update(insertStaffSQL, "dataSource");
        log.debug("newStaffNum:" + newStaffNum);

        // 3-将不需要不满足下发的坐席删除，防止中途规则配置的人或组删除
        String deleteStaffSQL = "Delete From Hst_Rule_Issue_Control" +
                " Where Staff_Id Not In" +
                "       (Select Staff_Id" +
                "          From Staff" +
                "         Where Find_In_Set(Staff_Id, '" + ruleStaff + "') > 0" +
                "   And ((auto_allocation = 0) " +
                " 	or (auto_allocation = 1 And starttime>now() And endtime>now() And starttime is not null And endtime is not null)" +
                " 	or (auto_allocation = 1 And starttime<now() And endtime<now() And starttime is not null And endtime is not null))" +
                "   And Workstatus = 'ONLINE')" +
                "   And Rule_Id = " + Rule_Id + "" +
                "   And Assign_Date = Date_Format(Now(), '%Y-%m-%d')";
        log.debug("deleteStaffSQL:" + deleteStaffSQL);
        eliteBean.update(deleteStaffSQL, "dataSource");
        return reFlag;
    }
}
